package com.surfilter.mq.util;

import com.google.gson.Gson;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class JsonUtils {
	
	private static Logger logger = LoggerFactory.getLogger(JsonUtils.class);
	
	private static Gson json = new Gson();
	
	public static String getJsonStringByObject(Object obj){
		return json.toJson(obj);
	}
	
	@SuppressWarnings("unchecked")
	public static Object getObjectByJsonString(String jsonStr, Class classType){
		Object obj = null;
		try{
			obj = json.fromJson(jsonStr, classType);
		}catch(Exception e){
			e.printStackTrace();
			logger.error("json串:{}解析异常", jsonStr, e);
		}
		return obj;
	}
	
	@SuppressWarnings("unchecked")
	public static Object getObjectByJsonString(String jsonStr, Type type){
		Object obj = null;
		try{
			obj = json.fromJson(jsonStr, type);
		}catch(Exception e){
			e.printStackTrace();
			logger.error("json串:{}解析异常", jsonStr, e);
		}
		return obj;
	}
	
	
	public static void main(String[] args) throws IOException {
//		String str = "{\"wzurl\":\"quanerlianmeng.com\",\"icpRecode\":\"quanerlianmeng.com\",\"wzid\":\"3306336\",\"ztid\":\"10000627535\",\"isp_wzid\":\"14203\",\"scbbsj\":\"May 22, 2013 12:00:00 AM\",\"zjxgsj\":\"May 22, 2013 12:00:00 AM\",\"wzmc\":\"\",\"syurl\":\"www.quanerlianmeng.com\",\"wzfzr\":\"\",\"wzfzr_zjlx\":2,\"wzfzr_zjhm\":\"370826199001051291\",\"wzfzr_dhhm\":\"086-021-62378700-8001\",\"wzfzr_sjhm\":\"15901696810\",\"wzfzr_dzyj\":\"578811120@qq.com\",\"wzfzr_msn\":\"\",\"wzfzr_qq\":\"\",\"nrlx\":0,\"fwnr\":8388608,\"baxh\":\"\",\"lryhlx\":1,\"lr_yhm_id\":1148,\"bz\":\"\",\"yl1\":0,\"yl2\":0,\"yl3\":\"\",\"yl4\":\"\",\"yl5\":\"\",\"is_access\":1,\"is_send\":1,\"is_sendRedis\":0,\"is_day_check\":1,\"is_week_check\":1}";
//		getObjectByJsonString(str, IcpTarget.class);
//		IcpTarget tar = new IcpTarget();
//		tar.setZjxgsj(new Date());
//		String targe = getJsonStringByObject(tar);
//		IcpTarget tara = (IcpTarget)getObjectByJsonString(targe, IcpTarget.class);
//		System.out.println(tara.getZjxgsj());
//		String value = "[2.0,2.0,2.0,2.0,2]";
//		List<Integer> results = (List<Integer>)JsonUtils.getObjectByJsonString(value, ArrayList.class);
//		System.out.println(results);
		Map <String,String> map = new HashMap<String,String>();
		map.put("name", "chenhao");
		map.put("age", "18");
		map.put("ym", "chenhao.com");
		System.out.println(map);
		String string = getJsonStringByObject(map);
		System.out.println(string);
		String file = "d:/json.txt";
		String str = FileUtils.readFileToString(new File(file), "utf-8");
		List<Map<String,String>> map1 = (List<Map<String,String>>)JsonUtils.getObjectByJsonString(str, Object.class);
		System.out.println(map1.get(0));
	}
	
}
